import { WeilaCore } from 'weilasdk_lite';
import { getMerchant, followMerchant } from '../../../utils/apis';
import LongModule from 'long';
const Long = LongModule.default || LongModule;

Page({
  data: {
    images: [],
    shopName: '',
    shopRating: '',
    reviewCount: '',
    shopStatus: '',
    shopHours: '',
    shopAddress: '',
    shopLocation: '',
    introduction: '',
    mid: 0,
    sid: 0,
    lat: 0,
    lon: 0,
    phone: ''
  },
  
  onLoad(q: any) {
    // Page initialization code
    console.log("Page loaded with query:", q);
    (async () => {
      await this.showLoading('加载中...');
      let weilaCore: WeilaCore = getApp().globalData.weilaCore;
      let token = weilaCore.weila_get_storage_instance().getLoginToken()!;
      getMerchant(token, {
        mid: parseInt(q.id, 10)
      }).then((res) => {
        console.log("Merchant data:", res);
        // Parse the result and update data
        const merchant = res.data.merchant;
        wx.setNavigationBarTitle({
          title: merchant.name || '商家信息'
        });
        this.setData({
          shopName: merchant.name,
          shopAddress: merchant.address,
          shopLocation: merchant.township,
          introduction: merchant.intro,
          images: merchant.album || [], // Use album images if available
          sid: merchant.sid,
          mid: merchant.id,
          lat: merchant.lat,
          lon: merchant.lon,
          phone: merchant.phone
        });
      }).catch((err) => {
        console.error("Error fetching merchant data:", err);
      }).finally(() => {
        this.hideLoading(); // Hide loading mask
      });
    })();
  },
  
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // handleFindCar() {
  //   wx.navigateTo({
  //     url: '/pages/life/life-map/life-map'
  //   });
  // },
  
  onShareAppMessage() {
    wx.showToast({
      title: '分享功能未实现',
      icon: 'none'
    });
  },

  onFollow() {
    console.log("Follow button clicked");
    let weilaCore: WeilaCore = getApp().globalData.weilaCore;
    let token = weilaCore.weila_get_storage_instance().getLoginToken()!;
    followMerchant(token, {
      mid: this.data.mid
    }).then((res) => {
      console.log("Follow response:", res);
      wx.showToast({
        title: '关注成功',
        icon: 'success'
      });
    }).catch((err) => {
      console.error("Error following merchant:", err);
      wx.showToast({
        title: '关注失败',
        icon: 'none'
      });
    })
  },

  onSendMessage() {
    let weilaCore: WeilaCore = getApp().globalData.weilaCore;
    let userId = weilaCore.weila_get_storage_instance().getLoginUserInfo()!.userId!;
    let sessionId = Long.fromBits(userId, this.data.sid, true);
    console.log("Session ID:", sessionId.toString());

    wx.navigateTo({
      url: '/pages/sessions/session-chat/session-chat?sessionId=' + sessionId.toString() + '&lastMsgId=0'
    });

    console.log("Send message button clicked");
  },

  // Function to show the loading mask
  async showLoading(text: string): Promise<void> {
    return new Promise((resolve) => {
      this.setData(
        {
          loading: true,
          loadingText: text,
        },
        () => {
          resolve(); // Resolve the promise when setData callback is triggered
        }
      );
    });
  },

  // Function to hide the loading mask
  async hideLoading(): Promise<void> {
    return new Promise((resolve) => {
      this.setData(
        {
          loading: false,
          loadingText: '',
        },
        () => {
          resolve(); // Resolve the promise when setData callback is triggered
        }
      );
    });
  },

  async handleCall(): Promise<void> {
    console.log("Call button clicked");
    const phone = this.data.phone;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
        success: () => {
          console.log("Call successful");
        },
        fail: (err) => {
          console.error("Call failed:", err);
        }
      });
    } else {
      wx.showToast({
        title: '电话号码无效',
        icon: 'none'
      });
    }
  },

})
